package com.von.nhcf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.von.nhcf.constant.NhcfConstant;
import com.von.nhcf.entity.Admin;
import com.von.nhcf.entity.AdminExample;
import com.von.nhcf.exception.LoginAcctAlreadyExistedException;
import com.von.nhcf.exception.LoginFailureException;
import com.von.nhcf.mapper.AdminMapper;
import com.von.nhcf.service.AdminService;
import com.von.nhcf.util.EncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

/**
 * AdminService接口实现
 * @author von
 */
@Service
public class AdminServiceImpl implements AdminService {
    // 开启日志
    Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);
    /**
     * 自动配置AdminMapper对象
     */
    @Autowired
    AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public void saveAdmin(Admin admin) {
        // 密码md5加密
        String plaintext = admin.getUserPswd();
        String res = bCryptPasswordEncoder.encode(plaintext);
        admin.setUserPswd(res);
        // 获取添加日期
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = format.format(date);
        admin.setCreateTime(createTime);
        // 执行保存， 如果账户被占用会抛出异常
        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
            e.printStackTrace();
            // 检测当前捕获的异常对象， 如果是 DuplicateKeyException 类型说明是账号重复导致的
            if (e instanceof DuplicateKeyException) {
                // 抛出自定义的 LoginAcctAlreadyInUseException 异常
                throw new LoginAcctAlreadyExistedException(NhcfConstant.MESSAGE_LOGIN_ACCOUT_ALREADY_EXISTED);
            }
            // 如果当前捕获到的不是 DuplicateKeyException 类型的异常，则把当前捕获到的异常对象继续向上抛出
            throw e;
        }
    }

    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
        // 判断传入的账号密码是否为空
        if (loginAcct.isEmpty() || userPswd.isEmpty()) {
            throw new LoginFailureException(NhcfConstant.MESSAGE_LOGIN_ACCOUNT_OR_PWD_EMPTY);
        }
        // 根据登录账号查询 Admin 对象
        // 创建 AdminExample 对象
        AdminExample adminExample = new AdminExample();
        // 创建 Criteria 对象
        AdminExample.Criteria criteria = adminExample.createCriteria();
        // 在 Criteria 对象中封装查询条件
        criteria.andLoginAcctEqualTo(loginAcct);
        // 调用 AdminMapper 的方法执行查询
        List<Admin> list = adminMapper.selectByExample(adminExample);
        // 判断 Admin 对象是否为 null
        if (list == null || list.size() == 0) {
            throw new LoginFailureException(NhcfConstant.MESSAGE_LOGIN_FAILUIRE);
        }
        if (list.size() > 1) {
            throw new RuntimeException(NhcfConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }
        Admin admin = list.get(0);
        // 如果 Admin 对象为 null 则抛出异常
        if (admin == null) {
            throw new LoginFailureException(NhcfConstant.MESSAGE_LOGIN_FAILUIRE);
        }
        // 如果 Admin 对象不为 null 则将数据库密码从 Admin 对象中取出
        String userPswdDB = admin.getUserPswd();
        // 将表单提交的明文密码进行加密
        String userPswdForm = EncryptUtil.md5Encrypt(userPswd);
        // 对密码进行比较
        if (!Objects.equals(userPswdDB.toUpperCase(), userPswdForm.toUpperCase())) {
            // 如果比较结果是不一致则抛出异常
            throw new LoginFailureException(NhcfConstant.MESSAGE_LOGIN_FAILUIRE);
        }
        // 8.如果一致则返回 Admin 对象
        return admin;
    }

    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
        // 开启分页功能
        PageHelper.startPage(pageNum, pageSize);
        // 查询 Admin 数据
        List<Admin> adminList = adminMapper.selectAdminListByKeyword(keyword);
        //  印 adminList 的全类名
        logger.debug("adminList 的全类名是： "+adminList.getClass().getName());
        // 将 adminList 封装为 PageInfo
        PageInfo<Admin> pageInfo = new PageInfo<>(adminList);
        return pageInfo;
    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Admin getAdminById(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void updateAdminSelective(Admin admin) {
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    @Override
    public Admin getAdminByAccount(String account) {
        AdminExample example = new AdminExample();

        AdminExample.Criteria criteria = example.createCriteria();

        criteria.andLoginAcctEqualTo(account);

        List<Admin> list = adminMapper.selectByExample(example);

        Admin admin = list.get(0);

        return admin;
    }
}
